#TYLE_OPTS:= $(shell type c:\temp\tyleopts.txt)
#interesting: --param large-function-growth
#interesting optimization debug tool: -Winline
#smallest code: -fdefer-pop -foptimize-sibling-calls -frerun-cse-after-loop -fexpensive-optimizations -funit-at-a-time -fweb
#TYLE_OPTS=-fdefer-pop -foptimize-sibling-calls -frerun-cse-after-loop -fexpensive-optimizations -funit-at-a-time -fweb
#OPTIMIZATION=$(TYLE_OPTS) -march=i586 -fno-rtti 

 
CXX=g++

ifeq ($(TYLE_DEBUG),1)
	OPTIMIZATION = -g -O2 -march=i686 -fno-rtti -DDEBUG
	STRIPPING=
else
	OPTIMIZATION= -O3 -march=i686 -fno-rtti
	STRIPPING= -Wl,-s
endif

VERSION=1

CPPFLAGS=$(OPTIMIZATION) -DDEBUGLOGGING -DTYLE_VERSION=\"$(VERSION)\" -fmessage-length=0 -Isrc -DGCC_NEW -fexceptions

#todo $(word 1, $(shell cmd /c version.bat) )


#CPPFLAGS=$(CPPFLAGS_$(SYSTEM))


LINKER=$(CXX) $(STRIPPING) -static -lstdc++
LIBFLAGS=-Wl,-Map,out/tyle.map 

SOURCES=tyle.cc parser.cc object.cc expr.cc funcs.cc context.cc mstl.cc random.cc regexp.cc
PRJ=tyle
OUT=out
OPRJ=$(OUT)/$(PRJ)
LIB=$(OUT)/lib$(PRJ)
DLIB_WINDOWS=$(OPRJ).dll
DLIB_LINUX=$(LIB).so
VPATH=$(OUT) src

ifneq (,$(findstring Windows,$(OS)))
	CPPFLAGS+=-D__WIN__ -D__MSVCRT_VERSION__=0x0700 -DTYLE_BUILD_SHARED
	EXEEXT=.exe
	DLIB=$(DLIB_WINDOWS)
else
	CPPFLAGS+=-DNO_DLL -fPIC
	EXEEXT=
	DLIB=$(DLIB_LINUX)
endif

all:	tyle$(EXEEXT)
tyle$(EXEEXT): tyler.cc $(OUT) $(DLIB)
	$(LINKER) $(CPPFLAGS) $< -o $(OUT)/$@ out/tyle.dll
		
.PHONY: export
$(PRJ): $(DLIB)

: in the future, do this:	$(CXX) $(SOURCES:%.cc=$(OUT)/%.o) -mno-cygwin -o $(OPRJ).$(DLEXT) -lm -mdll -Wl,-s,--out-implib,lib$(PRJ).lib,--verbose


$(DLIB_WINDOWS): $(SOURCES:%.cc=$(OUT)/%.o) 
	$(LINKER) $(LIBFLAGS) $^ -o $@ -fexceptions -lm -shared -lgdi32 -Wl,--dll
	
#dlltool --base-file $(OPRJ).base --input-def $< --output-lib $(LIB).lib --dllname $@

$(DLIB_LINUX): $(SOURCES:%.cc=$(OUT)/%.o) 
	$(LINKER) $(LIBFLAGS) --enable-auto-import -shared -Wl,-soname,libtyle.so -o $@ $^ -lpthread -lrt -lreadline

#$(DLIB_LINUX):
#	ln -s lib$(PRJ).so.$(SOVERSION) $(DLIB_LINUX)
#	dlltool --base-file $(OPRJ).base --input-def $< --output-lib $(LIB) --dllname $(PRJ).dll 

$(OUT):
	@mkdir out

$(OUT)/%.d: %.cc
	@set -e; rm -f $@; \
	echo $(CXX) -M $(CPPFLAGS) $< $@.$$$$; \
	$(CXX) -M $(CPPFLAGS) $< > $@.$$$$; \
	sed 's,\($*\)\.o[ :]*,$(OUT)/\1.o $@ : ,g' < $@.$$$$ > $@; \
	rm -f $@.$$$$

$(OUT)/%.o: %.cc %.d
	$(CXX) -c $(CPPFLAGS) $< -o $@
		
-include $(SOURCES:%.cc=$(OUT)/%.d)

export: 
	rm -rf export
	mkdir -p export
	cp out/libtyle.so export/
	cp out/tyle export/
	cp src/tyle.h export/
	cp resources/* export/
	cp tylecode/* export/
.PHONY: export clean oclean
clean:
	rm -f $(OUT)/*
oclean:
	rm -f $(OUT)/*.o

